// JavaScript Document

function isVisible(selector) {
	return $(selector).is(':visible');
}

function translate(q) {
	// example:http://google.com/translate_t?text=how+are+you&langpair=en|es
	try {
		netscape.security.PrivilegeManager
				.enablePrivilege("UniversalBrowserRead");
	} catch (e) {
		alert("Permission UniversalBrowserRead denied: " + e);
	}
	try {
		var myData = new Object;
		myData.text = q;
		myData.langpair = 'en|es';

		$.ajax( {
			url : "http://google.com/translate_t",
			type : 'GET',
			data : myData,
			dataType : 'html',
			timeout : 100000,
			error : errorFunction,
			success : function(html) {
				alert(html);
				$("#translate").hide();
				$("#translate").html(html);
				$("#translate").html($("#result_box").text());
				$("#translate").show();
			}
		});
	} catch (e) {
		alert("Translation Error: " + printObject(e));
	}
}

function handleEnterKey(field, event, fcn) {
	var keyCode = event.keyCode ? event.keyCode : event.which ? event.which
			: event.charCode;
	if (keyCode == 13) {
		fcn();
		return false;
	} else
		return true;
}

function isDefined(variable) {
	return (typeof (window[variable]) == "undefined") ? false : true;
}

function showPage(url, contentArea) {
	$.ajax( {
		url : url,
		type : 'GET',
		dataType : 'html',
		timeout : 100000,
		error : errorFunction,
		success : function(html) {
			$(contentArea).html(html);
		}
	});
}

function errorFunction(XMLHttpRequest, textStatus, errorThrown) {
	alert("XMLHttpRequest = " + printObject(XMLHttpRequest) + "\ntextStatus = "
			+ printObject(textStatus) + "\nerrorThrown = " + printObject(errorThrown));
}

function printObject(obj) {
	var str = ""; // variable which will hold property values
	for (prop in obj) {
		str += prop + " value : " + arguments[prop] + "\n";// Concate prop and
		// its value from
		// object
	}
	return str;
}

// chk if an object is an array or not.
function isArray(obj) {
	// returns true is it is an array
	if (obj.constructor.toString().indexOf("Array") == -1)
		return false;
	else
		return true;
}

function in_array(needle, haystack) {
	var found = false;

	for (key in haystack) {
		if (haystack[key] == needle) {
			found = true;
			break;
		}
	}

	return found;
}

// gets the value of a radio button group by name
function getRadioValue(radioButtonGroupName) {
	try {
		var rb_value;
		$('[name=' + radioButtonGroupName + ']').each(function() {
			if (this.checked) {
				rb_value = this.value;
			}
		});
		return rb_value;
	} catch (e) {
		alert(e);
	}
}

function GET(name) {
	name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
	var regexS = "[\\?&]" + name + "=([^&#]*)";
	var regex = new RegExp(regexS);
	var results = regex.exec(window.location.href);
	if (results == null)
		return "";
	else
		return results[1];
}

var BrowserDetect = {
	init : function() {
		this.browser = this.searchString(this.dataBrowser)
				|| "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
				|| this.searchVersion(navigator.appVersion)
				|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString : function(data) {
		for ( var i = 0; i < data.length; i++) {
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch
					|| data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			} else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion : function(dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1)
			return;
		return parseFloat(dataString.substring(index
				+ this.versionSearchString.length + 1));
	},
	dataBrowser : [ {
		string : navigator.userAgent,
		subString : "OmniWeb",
		versionSearch : "OmniWeb/",
		identity : "OmniWeb"
	}, {
		string : navigator.vendor,
		subString : "Apple",
		identity : "Safari"
	}, {
		prop : window.opera,
		identity : "Opera"
	}, {
		string : navigator.vendor,
		subString : "iCab",
		identity : "iCab"
	}, {
		string : navigator.vendor,
		subString : "KDE",
		identity : "Konqueror"
	}, {
		string : navigator.userAgent,
		subString : "Firefox",
		identity : "Firefox"
	}, {
		string : navigator.vendor,
		subString : "Camino",
		identity : "Camino"
	}, { // for newer Netscapes (6+)
				string : navigator.userAgent,
				subString : "Netscape",
				identity : "Netscape"
			}, {
				string : navigator.userAgent,
				subString : "MSIE",
				identity : "Explorer",
				versionSearch : "MSIE"
			}, {
				string : navigator.userAgent,
				subString : "Gecko",
				identity : "Mozilla",
				versionSearch : "rv"
			}, { // for older Netscapes (4-)
				string : navigator.userAgent,
				subString : "Mozilla",
				identity : "Netscape",
				versionSearch : "Mozilla"
			} ],
	dataOS : [ {
		string : navigator.platform,
		subString : "Win",
		identity : "Windows"
	}, {
		string : navigator.platform,
		subString : "Mac",
		identity : "Mac"
	}, {
		string : navigator.platform,
		subString : "Linux",
		identity : "Linux"
	} ]

};
BrowserDetect.init();

function validateEmail(emailAddr) {
	var message;
	var valid;
	// do a basic check for null, zero-length string, ".", "@",
	// and the absence of spaces
	if (emailAddr == null || emailAddr.length == 0
			|| emailAddr.indexOf(".") == -1 || emailAddr.indexOf("@") == -1
			|| emailAddr.indexOf(" ") != -1) {
		message = "Make sure the email address does not contain any spaces and is otherwise valid (e.g., contains the \"commercial at\" @ sign).";
		valid = false;
		return message;
	}
	/*
	 * The local part cannot begin or end with a "." Regular expression
	 * specifies: the group of characters before the @ symbol must be made up of
	 * at least two word characters, followed by zero or one period char,
	 * followed by at least 2 word characters. regex=/(^\w{2,}\.?\w{1,})@/;
	 * _match = regex.exec(emailAddr);
	 * 
	 * if ( _match){ user=RegExp.$1; // alert("user: "+user); } else {
	 * message="Make sure the user name is more than two characters, "+ "does
	 * not begin or end with a period (.), or is not otherwise "+ "invalid!";
	 * valid=false; return message; }
	 */
	// get the domain after the @ char
	// first take care of domain literals like @[19.25.0.1], however rare
	regex = /@(\[\d{1,3}\.\d{1,3}\.\d{1,3}.\d{1,3}\])$/;
	_match = regex.exec(emailAddr);

	if (_match) {
		domain = RegExp.$1;
		valid = true;
		return valid;
	} else {
		/*
		 * The @ character followed by at least two chars that are not a period
		 * (.), followed by a period, followed by zero or one instances of two
		 * or more characters ending with a period, followed by two-three chars
		 * that are not periods
		 */
		regex = /@(\w{2,}\.(\w{2,}\.)?[a-zA-Z]{2,3})$/;
		_match = regex.exec(emailAddr);
		if (_match) {
			domain = RegExp.$1;
			// alert("domain: "+domain);
		} else {
			message = "The domain portion of the email had less than 2 chars "
					+ "or was otherwise invalid!";
			valid = false;
			return message;
		}
	}// end domain check
	valid = true;
	return valid;
}

function scrollDown(id) {
	scrollToBottom(id);
}

function ScrollToElement(id) {
	var theElement = document.getElementById(id);
	var selectedPosX = 0;
	var selectedPosY = 0;

	while (theElement != null) {
		selectedPosX += theElement.offsetLeft;
		selectedPosY += theElement.offsetTop - 15;
		theElement = theElement.offsetParent;
	}

	window.scrollTo(selectedPosX, selectedPosY);

}

// UI FUNCTIONS
$.fn.crossFade = function(speed, fadeToImage) {
	$(this).fadeOut(speed, function() {
		$(this).attr('src', fadeToImage);
		$(this).fadeIn(speed);
	});
};

$.fn.divCrossFade = function(speed, fadeToImage, attr) {
	$(this).fadeOut(speed, function() {
		// $(this).attr('background-image', 'url('+fadeToImage+');');
			// $(this).css({'background-image':
			// "url('"+fadeToImage+"')"});
			$(this).html(
					'<img src="' + fadeToImage
							+ '" hspace="10" vspace="10" id="main_image" '
							+ attr + ' />').fadeIn(speed);
		});
};

function pageLoaded() {
	$("input").addClass("ui-corner-all");
	$(":button").addClass("ui-state-default ui-corner-all");
	$(".box").addClass("ui-corner-all");

	$(".active_page").addClass("ui-corner-top");
	$(".non_active_page").removeClass("ui-corner-all");
	$(".non_active_page").addClass("ui-corner-top");

	$(".CollapsiblePanelTab").addClass('ui-state-default ui-corner-all');
	$(".CollapsiblePanel").addClass('ui-widget-content ui-corner-all');
}

function scrollToBottom(elementId) {
	// /<summary>Scrolls the element to the bottom.</summary>
	var element = document.getElementById(elementId);
	element.scrollTop = element.scrollHeight;
}

// jquery live binding, effects all new elements created
$(':button').live("mouseover", function() {
	$(this).addClass('ui-state-hover');
});
$(':button').live("mouseout", function() {
	$(this).removeClass('ui-state-hover');
});

$('.CollapsiblePanelTab').live("mouseover", function() {
	$(this).addClass('ui-state-hover')
});
$('.CollapsiblePanelTab').live("mouseout", function() {
	$(this).removeClass('ui-state-hover')
});

$('.CollapsiblePanelTab').live("click", function() {
	if ($(this).attr("active") == "true") {
		$(this).removeClass('ui-state-active');
		$(this).attr("active", "false");
	} else {
		$(this).addClass('ui-state-active');
		$(this).attr("active", "true");
	}
});

/**
 * Makes an ajax call to load the view of a class (model) object
 * 
 * @param model
 *            The model (class) to load
 * @param primary_key_value
 *            The primary key value of the model to load
 * @param db_name
 *            [optional] The name of the database, must be provided once for
 *            initialization
 * @return
 */
function openClassView(model, primary_key_value, db_name) {
	var myData = new Object;
	myData.model = model;
	myData.primary_key_value = primary_key_value;
	$('#content').html('Loading...');

	if (db_name) {
		saved_db_name = db_name;
	}

	$.ajax( {
		url : saved_db_name + '_mvc/View/tabbed_class_viewer.php',
		type : 'GET',
		dataType : 'html',
		data : myData,
		success : function(html) {
			$('#content').html(html);
			$('#content').fadeIn();
			prepareTabs();
		}
	});
}

function prepareTabs() {
	$("#tabs").tabs( {
		spinner : "Loading...",
		fx : {
			opacity : 'toggle'
		},
		cache : false
	});

	$(".loading").hide();
	$('#tabs').ajaxComplete(function(event1, request, settings) {
		pageLoaded();
		console.log(event1);
		console.log(request);
		console.log(settings);
	});
	$(".ui-tabs-nav a").css("padding", ".2em");
	pageLoaded();
	$("a").addClass("ui-state-default ui-corner-all");
	$('a').live("mouseover", function() {
		$(this).addClass('ui-state-hover')
	});
	$('a').live("mouseout", function() {
		$(this).removeClass('ui-state-hover')
	});
}

function updateSuccessful(result) {
	if (result == false) {
		alert("Update failed. Your page is out of sync with the database. REFRESHING PAGE.");
		location.reload(true);
	}
}